import { Controller,Get,Query,UseGuards, Req} from '@nestjs/common';
import { EmailService } from "../../services/email/email.service";
import { ApiTags, ApiResponse, ApiQuery, ApiBody,ApiBearerAuth} from '@nestjs/swagger';
import { AuthGuard } from '@nestjs/passport';
import { UserService } from "../../services/user/user.service";
import {password} from '../../utils/_crypto';
import { AuthService } from '../../services/auth/auth.service';
import { Request } from 'express';
import { ConfigService } from '../../config/config.service';

@ApiTags('email')
@Controller('api/email')
export class EmailController {
  projectConfig:ConfigService;
  constructor(
    private readonly emailService:EmailService,
    private readonly userService: UserService,
    private readonly authService: AuthService
  ){
    this.projectConfig=new ConfigService('src/env/project.env');
  }
  @Get('send')
  send(@Query() querys){
    this.emailService.sendTo('<1741750591@qq.com>','<1741750591@qq.com>','hello','word');
  }

  //邮箱激活
  @Get('active')
  @ApiResponse({ status: 403, description: 'Forbidden.'})
  @ApiResponse({ status: 200, description: '邮箱已发送'})
  @ApiResponse({ status: 201, description: '用户不存在或邮箱未填写'})
  @ApiQuery({name: 'user_id',description: '用户id',required:true,example:31,type:Number})
  async active(@Req() req:Request){
    const querys = req.query,hostname = `${this.projectConfig.get('protocol')}://${this.projectConfig.get('ip')}:${this.projectConfig.get('port')}`;
    const user=await this.userService.findOneByID(querys.user_id)
    if(user&&user.email){
      const obj=await this.authService.activeMail(user.id)
      const activeUrl = hostname+'/api/email/verify?token='+obj.token;
      await this.emailService.sendTo(
      '<1741750591@qq.com>'
      ,`<${user.email}>`
      ,'邮箱验证'
      ,'验证地址：'+activeUrl
      );
      return {
        code:200,
        msg:"邮箱已发送",
        activeUrl:activeUrl
      }
    }else{
      return {
        code:201,
        msg:"用户不存在或邮箱未填写"
      }
    }
    
  }

  @Get('verify')
  @ApiResponse({ status: 403, description: 'Forbidden.'})
  @ApiResponse({ status: 200, description: '邮箱激活成功.'})
  @ApiResponse({ status: 201, description: 'token无效或已过期'})
  @ApiResponse({ status: 202, description: '激活邮箱与绑定邮箱不符，激活失败'})
  @ApiQuery({name: 'token',description: '邮箱token',required:true,type:String})
  async verfiy(@Query() querys){
    const info=this.authService.verfiyMail(querys.token)
    if(info==false){
      return {
        code:201,
        msg:"token无效或已过期"
      }
    }
    let user=await this.userService.findOneByID(info.userId);
    if(user.email!==info.userEmail){
      return {
        code:202,
        msg:"激活邮箱与绑定邮箱不符，激活失败"
      }
    }
    user.email_status=1;
    this.userService.saveUser(user);
    return {
      code:200,
      msg:user.email+"邮箱激活成功"
    }
  }
}
